<?php


namespace app\finance\controller;


use app\base\BaseController;
use think\Exception;
use think\facade\Db;
use think\facade\View;

class PurchasePayment extends BaseController
{
    protected $title='采购付款单';
    protected $table='money_order';
    protected $tableMx='money_order_contract_detail';
    protected $mType=3;
    protected $flowType=5;//审批表的type
    public function index()
    {

        $param=$this->request->param();
        if (request()->isAjax()) {
            $where[]=['mo.status','>',-1];
            $where[]=['mocd.status','>',-1];
            $where[]=['mo.type','=',$this->mType];

            if (isset($this->param['status'])&&$this->param['status']){
                $where[]=['mo.status','=',$this->param['status']];
            }
            if (isset($this->param['pName'])&&$this->param['pName']){
                $where[]=['py.name','like','%'.$this->param['pName'].'%'];
            }
            if (isset($this->param['saleUnitName'])&&$this->param['saleUnitName']){
                $where[]=['d.title','like','%'.$this->param['saleUnitName'].'%'];
            }
            if (isset($this->param['htNum'])&&$this->param['htNum']){
                $where[]=['sc.orderNum','like','%'.$this->param['htNum'].'%'];
            }
            if (isset($this->param['hsContract'])&&$this->param['hsContract']){
                $where[]=['mocd.hsContract','like','%'.$this->param['hsContract'].'%'];
            }
            if (isset($this->param['orderDate'])&&$this->param['orderDate']){
                $dates=explode('~',$this->param['orderDate']);
                $where[]=['mo.orderDate','between',$dates];
            }
            foreach (["buyCode","name","specs","brand"] as $v){
                if (isset($param[$v])&&$param[$v]){
                    $where[]=['md.'.$v,'like','%'.$param[$v].'%'];
                }
            }
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $list = Db::name('money_order_contract_detail')
                ->alias('mocd')
                ->leftJoin('money_order mo','mo.id=mocd.orderId')
                ->leftJoin('material_dossier md','md.id=mocd.mdId')
                ->leftJoin('purveyor py','py.id=mo.purveyorId')
                ->leftJoin('admin ad','ad.id=mo.checkId')
                ->leftJoin('department d','d.id=mo.saleUnit')
                ->leftJoin('sale_contract_detail scd','scd.id=mocd.contractMxId')
                ->leftJoin('sale_contract sc','sc.id=mocd.contractId')
                ->where($where)
                ->field("mocd.*,py.name as pName,ad.name as payName,py.bank as khh,py.bankCard as khzh,mo.orderNum as fkNum,mo.orderDate,mo.status as orderStatus,mo.payType,
                sc.orderNum as cgHt,scd.bjNum,scd.bjMoney,mo.payDate,d.title as saleUnitName,
                md.brand,md.name as mdName,md.specs,md.buyCode,md.unit")
                ->order('mo.id DESC')
                ->paginate($rows)->each(function ($item){
                    $fkbl=0;
                    if ($item['contactMoney']>0){
                        $fkbl=$item['money']/$item['contactMoney'];
                        $fkbl=round($fkbl,2);
                    }
                    $item['fkbl']=$fkbl;
                    return $item;
                });
            return table_assign(0, '', $list);
        } else {
            return view();
        }
    }

    public function add()
    {
        $param=$this->param;
        $id=$param['id']??0;
        if ($this->request->post()){
            $mx=$param['mx']??[];
            if (!$param['flow_id']||!$param['check_admin_ids']){
                return to_assign(1,'请选择审批人或审批模板');
            }
            if (!$param['purveyorId']||!$mx){
                return  to_assign(1,'参数缺失');
            }
            $mxid=$mx['mxid']??[];
            $contractId=$mx['contractId']??[];
            $contractMxId=$mx['contractMxId']??[];
            $contractOrder=$mx['contractOrder']??[];
            $contactMoney=$mx['contactMoney']??[];
            $dhMoney=$mx['dhMoney']??[];
            $dhUnpayMoney=$mx['dhUnpayMoney']??[];
            $payedMoney=$mx['payedMoney']??[];
            $unPayMoney=$mx['unPayMoney']??[];
            $hsContract=$mx['hsContract']??[];
            $money=$mx['money']??[];
            $mdId=$mx['mdId']??[];
            $countMoney=0;
            foreach ($money as $v){
                $countMoney+=$v;
            }
            $counContactMoney=0;
            foreach ($contactMoney as $v){
                $counContactMoney+=$v;
            }
            unset($param['mx']);
            $param['money']=$countMoney;
            $param['update_time'] = time();
            $param['contactMoney']=$counContactMoney;
            $flow_list = Db::name('Flow')->where('id',$param['flow_id'])->value('flow_list');
            $flow = unserialize($flow_list);
            $haseFolow=Db::name('FlowStep')->where(['action_id'=>$param['id'],'type'=>$this->flowType,'delete_time'=>0])->find();
            Db::startTrans();
            try {
                if ($id > 0&&$haseFolow) {
                    $param['check_status']=1;
                    $param['status']=3;
                    Db::name($this->table)->strict(false)->update($param);
                    if (!isset($param['check_admin_ids'])) {
                        if($flow[0]['flow_type'] == 1){
                            //部门负责人
                            $leader = get_department_leader($this->uid);
                            if($leader == 0){
                                return to_assign(1,'审批流程设置有问题：当前部门负责人还未设置，请联系HR或者管理员');
                            }
                            else{
                                $param['check_admin_ids'] = $leader;
                            }
                        }
                        else if($flow[0]['flow_type'] == 2){
                            //上级部门负责人
                            $leader = get_department_leader($this->uid,1);
                            if($leader == 0){
                                return to_assign(1,'审批流程设置有问题：上级部门负责人还未设置，请联系HR或者管理员');
                            }
                            else{
                                $param['check_admin_ids'] = $leader;
                            }
                        }
                        else{
                            $param['check_admin_ids'] = $flow[0]['flow_uids'];
                        }
                        foreach ($flow as $key => &$value){
                            $value['action_id'] = $param['id'];
                            $value['sort'] = $key;
                            $value['type'] = $this->flowType;
                            $value['create_time'] = time();
                        }
                        //增加审核流程
                        Db::name('FlowStep')->strict(false)->field(true)->insertAll($flow);
                    }
                    else{
                        $flow_step = array(
                            'action_id' => $param['id'],
                            'type' => $this->flowType,
                            'flow_uids' => $param['check_admin_ids'],
                            'create_time' => time()
                        );
                        //增加审核流程
                        Db::name('FlowStep')->strict(false)->field(true)->insertGetId($flow_step);
                    }
//添加提交申请记录
                    $checkData=array(
                        'action_id' => $id,
                        'check_user_id' => $this->uid,
                        'content' => '重新提交申请',
                        'type' => $this->flowType,
                        'check_time' => time(),
                        'create_time' => time()
                    );
                    Db::name('FlowRecord')->strict(false)->field(true)->insertGetId($checkData);

//                    add_log('edit', $param['id'], $param,$this->title);
                    //发送消息通知
                    $msg=[
                        'from_uid'=>$this->uid,
                        'title'=>'采购付款审批',
                        'action_id'=>$id
                    ];
                    $users = $param['check_admin_ids'];
                    sendMessage($users,54,$msg);
                }else{
                    $param['status']=3;
                    $param['check_status']=1;
                    if ($id){
                        Db::name($this->table)->strict(false)->update($param);
                        add_log('edit', $id, $this->param,$this->title);
                    }else{
                        unset($param['id']);
                        $param['createId']=$this->uid;
                        $param['orderNum']=dJBHBySql($this->table,'orderNum',getOrderPrefix($this->controller).date('Ymd'),false,1000);
                        $param['type']=$this->mType;
                        $param['departId']=$this->did;

                        $param['create_time'] = time();

                        $id=Db::name($this->table)->strict(false)->insertGetId($param);
                        add_log('add', $id, $this->param,$this->title);
                    }
                    if (!isset($param['check_admin_ids'])) {
                        if($flow[0]['flow_type'] == 1){
                            //部门负责人
                            $leader = get_department_leader($this->uid);
                            if($leader == 0){
                                return to_assign(1,'审批流程设置有问题：当前部门负责人还未设置，请联系HR或者管理员');
                            }
                            else{
                                $param['check_admin_ids'] = $leader;
                            }
                        }
                        else if($flow[0]['flow_type'] == 2){
                            //上级部门负责人
                            $leader = get_department_leader($this->uid,1);
                            if($leader == 0){
                                return to_assign(1,'审批流程设置有问题：上级部门负责人还未设置，请联系HR或者管理员');
                            }
                            else{
                                $param['check_admin_ids'] = $leader;
                            }
                        }
                        else{
                            $param['check_admin_ids'] = $flow[0]['flow_uids'];
                        }

                        foreach ($flow as $key => &$value){
                            $value['action_id'] = $id;
                            $value['sort'] = $key;
                            $value['type'] = $this->flowType;
                            $value['create_time'] = time();
                        }
                        //增加审核流程
                        Db::name('FlowStep')->strict(false)->field(true)->insertAll($flow);
                    }else{
                        $flow_step = array(
                            'action_id' => $id,
                            'type' => $this->flowType,
                            'flow_uids' => $param['check_admin_ids'],
                            'create_time' => time()
                        );
                        //增加审核流程
                        Db::name('FlowStep')->strict(false)->field(true)->insertGetId($flow_step);

                    }
                    //发送消息通知
                    $msg=[
                        'from_uid'=>$this->uid,
                        'title'=>'采购付款审批',
                        'action_id'=>$id
                    ];
                    $users = $param['check_admin_ids'];
                    sendMessage($users,54,$msg);
                }



            foreach ($contractId as $key=>$v){
                $mxData=[
                    'orderId'=>$id,
                    'contractId'=>$contractId[$key]??'',
                    'contractMxId'=>$contractMxId[$key]??'',
                    'mdId'=>$mdId[$key]??'',
                    'purveyorId'=>$param['purveyorId'],
                    'type'=>$this->mType,
                    'money'=>$money[$key]??'',
                    'contactMoney'=>$contactMoney[$key]??'',
                    'contractOrder'=>$contractOrder[$key]??'',
                    'dhMoney'=>$dhMoney[$key]??0,
                    'dhUnpayMoney'=>$dhUnpayMoney[$key]??0,
                    'payedMoney'=>$payedMoney[$key]??0,
                    'unPayMoney'=>$unPayMoney[$key]??0,
                    'hsContract'=>$hsContract[$key]??0,
                    'createId'=>$this->uid,
                    'departId'=>$this->did,
                    'mocdType'=>2,
                    'create_time'=>time(),
                    'update_time'=>time(),
                ];
                if (isset($mxid[$key])&&$mxid[$key]){
                    unset($mxData['create_time']);
                    $mxData['id']=$mxid[$key];
                }
                Db::name('money_order_contract_detail')->save($mxData);
            }
                Db::name('sale_contract_detail')->where('id','in',$contractMxId)
                    ->update(['isCgfkSelected'=>1]);
               Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return to_assign(1,'操作失败：'.$e->getMessage());
            }
            return  to_assign();

        }else{
            $punList=Db::name('purveyor')->where('status',1)->where('dw_type',1)->field('id,name')->select();
            $detail=[];
            $mxList=[];
            $countPrice=0;
            if ($id){
                $detail=Db::name($this->table)
                    ->alias('mo')
                    ->leftJoin('purveyor p','p.id=mo.purveyorId')
                    ->where('mo.id',$id)
                    ->field("mo.*,p.bank,p.bankCard")
                    ->find();
                $mxList=Db::name('money_order_contract_detail')
                    ->alias('mocd')
                    ->leftJoin('material_dossier md','md.id=mocd.mdId')
                    ->where('mocd.status','>',-1)
                    ->where('mocd.orderId',$id)
                    ->field('mocd.*,md.brand,md.name as mdName,md.specs,md.buyCode,md.unit')
                    ->select()->each(function ($item){
                        $fkbl=0;
                        if ($item['contactMoney']>0){
                            $fkbl=$item['money']/$item['contactMoney'];
                            $fkbl=round($fkbl,2);
                        }
                        $item['fkbl']=$fkbl;
                        return $item;
                    });
                $countPrice=Db::name('money_order_contract_detail')
                    ->where('status','>',-1)
                    ->where('orderId',$id)->sum('money');
            }
            View::assign('countPrice',$countPrice);
            View::assign('punList',$punList);

            View::assign('id',$id);
            View::assign('mxList',$mxList);
            $is_check_admin = 0;
            $is_create_admin = 0;
            $check_record=[];
            if (!$id){
                $flows = get_cate_department_flows(26,$this->did);
            }else{
                $status=Db::name($this->table)->where('id',$id)->value('status');

                $flows = Db::name('FlowStep')->where(['action_id'=>$detail['id'],'type'=>$this->flowType,'sort'=>$detail['check_step_sort'],'delete_time'=>0])->find();

                $detail['check_user'] = '-';
                $detail['copy_user'] = '-';
                $check_user_ids = [];

                if ($flows&&$status!=1){
                    if($detail['check_status']==1){
                        if($flows['flow_type']==1){
                            $detail['check_user'] = '部门负责人';
                            $check_user_ids[]=get_department_leader($detail['createId']);
                        }
                        else if($flows['flow_type']==2){
                            $detail['check_user'] = '上级部门负责人';
                            $check_user_ids[]=get_department_leader($detail['createId'],1);
                        }
                        else{
                            $check_user_ids = explode(',',$flows['flow_uids']);
                            $check_user = Db::name('Admin')->where('id','in',$flows['flow_uids'])->column('name');
                            $detail['check_user'] = implode(',',$check_user);
                        }
                    }
                }else{
                    $flows = get_cate_department_flows(26,$this->did);
                }

                if($detail['copy_uids'] !=''){
                    $copy_user = Db::name('Admin')->where('id','in',$detail['copy_uids'])->column('name');
                    $detail['copy_user'] = implode(',',$copy_user);
                }

                if($detail['createId'] == $this->uid){
                    $is_create_admin = 1;
                }

                $detail['create_user']=Db::name('admin')
                    ->where('id',$detail['createId'])->value('name');
                if(in_array($this->uid,$check_user_ids)){
                    $is_check_admin = 1;
                    //当前审核节点详情
                    $step = Db::name('FlowStep')->where(['action_id'=>$detail['id'],'type'=>$this->flowType,'sort'=>$detail['check_step_sort'],'delete_time'=>0])->find();
                    if($step['flow_type'] == 4){
                        $check_count = Db::name('FlowRecord')->where(['action_id'=>$detail['id'],'type'=>$this->flowType,'step_id'=>$step['id'],'check_user_id'=>$this->uid])->count();
                        if($check_count>0){
                            $is_check_admin = 0;
                        }
                    }
                }
                $check_record = Db::name('FlowRecord')->field('f.*,a.name,a.thumb')
                    ->alias('f')
                    ->join('Admin a', 'a.id = f.check_user_id', 'left')
                    ->where(['f.action_id'=>$detail['id'],'f.type'=>$this->flowType])
                    ->order('check_time desc')
                    ->select()->toArray();
                foreach ($check_record as $kk => &$vv) {
                    $vv['check_time_str'] = date('Y-m-d H:i', $vv['check_time']);
                    $vv['status_str'] = '提交';
                    if($vv['status'] == 1){
                        $vv['status_str'] = '审核通过';
                    }
                    else if($vv['status'] == 2){
                        $vv['status_str'] = '审核拒绝';
                    }
                    if($vv['status'] == 3){
                        $vv['status_str'] = '撤销';
                    }
                }
            }
            View::assign('is_create_admin', $is_create_admin);
            View::assign('flows', $flows);
            View::assign('detail',$detail);
            View::assign('is_check_admin', $is_check_admin);
            View::assign('check_record', $check_record);
            View::assign('uid', $this->uid);
            View::assign('flowType', $this->flowType);
            $departLis=get_department();
            View::assign('departList',$departLis);
            return view('form');
        }
    }

    public function save()
    {
        $param=$this->param;
        $id=$param['id']??0;
        if ($this->request->post()){
            $mx=$param['mx']??[];
            if (!$param['purveyorId']||!$mx){
                return  to_assign(1,'参数缺失');
            }
            $mxid=$mx['mxid']??[];
            $contractId=$mx['contractId']??[];
            $contractMxId=$mx['contractMxId']??[];
            $contractOrder=$mx['contractOrder']??[];
            $contactMoney=$mx['contactMoney']??[];
            $dhMoney=$mx['dhMoney']??[];
            $dhUnpayMoney=$mx['dhUnpayMoney']??[];
            $payedMoney=$mx['payedMoney']??[];
            $unPayMoney=$mx['unPayMoney']??[];
            $money=$mx['money']??[];
            $hsContract=$mx['hsContract']??[];
            $mdId=$mx['mdId']??[];
            $countMoney=0;
            foreach ($money as $v){
                $countMoney+=$v;
            }
            $counContactMoney=0;
            foreach ($contactMoney as $v){
                $counContactMoney+=$v;
            }
            unset($param['mx']);
            $param['money']=$countMoney;
            $param['update_time'] = time();
            $param['contactMoney']=$counContactMoney;
            Db::startTrans();
            try {
                if ($id){
                    Db::name($this->table)->strict(false)->update($param);
                    add_log('edit', $id, $this->param,$this->title);
                }else{
                    unset($param['id']);
                    $param['createId']=$this->uid;
                    $param['orderNum']=dJBHBySql($this->table,'orderNum',getOrderPrefix($this->controller).date('Ymd'),false,1000);
                    $param['type']=$this->mType;
                    $param['departId']=$this->did;

                    $param['create_time'] = time();

                    $id=Db::name($this->table)->strict(false)->insertGetId($param);
                    add_log('add', $id, $this->param,$this->title);
                }
                foreach ($contractId as $key=>$v){
                    $mxData=[
                        'orderId'=>$id,
                        'contractId'=>$contractId[$key]??'',
                        'contractMxId'=>$contractMxId[$key]??'',
                        'mdId'=>$mdId[$key]??'',
                        'purveyorId'=>$param['purveyorId'],
                        'type'=>$this->mType,
                        'money'=>$money[$key]??'',
                        'contactMoney'=>$contactMoney[$key]??'',
                        'contractOrder'=>$contractOrder[$key]??'',
                        'dhMoney'=>$dhMoney[$key]??0,
                        'dhUnpayMoney'=>$dhUnpayMoney[$key]??0,
                        'payedMoney'=>$payedMoney[$key]??0,
                        'unPayMoney'=>$unPayMoney[$key]??0,
                        'hsContract'=>$hsContract[$key]??0,
                        'createId'=>$this->uid,
                        'departId'=>$this->did,
                        'mocdType'=>2,
                        'create_time'=>time(),
                        'update_time'=>time(),
                    ];
                    if (isset($mxid[$key])&&$mxid[$key]){
                        unset($mxData['create_time']);
                        $mxData['id']=$mxid[$key];
                    }
                    Db::name('money_order_contract_detail')->save($mxData);
                }
                Db::name('sale_contract_detail')->where('id','in',$contractMxId)
                    ->update(['isCgfkSelected'=>1]);
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return to_assign(1,'操作失败：'.$e->getMessage());
            }
            return  to_assign();

        }else{
            $punList=Db::name('purveyor')->where('status',1)->where('dw_type',1)->field('id,name')->select();
            $detail=[];
            $mxList=[];
            if ($id){
                $detail=Db::name($this->table)->where('id',$id)->find();
                $mxList=Db::name('money_order_contract_detail')
                    ->alias('mocd')
                    ->leftJoin('material_dossier md','md.id=mocd.mdId')
                    ->where('mocd.status','>',-1)
                    ->where('mocd.orderId',$id)
                    ->field('mocd.*,md.brand,md.name as mdName,md.specs,md.buyCode,md.unit')
                    ->select()->each(function ($item){
                        $fkbl=0;
                        if ($item['contactMoney']>0){
                            $fkbl=$item['money']/$item['contactMoney'];
                            $fkbl=round($fkbl,2);
                        }
                        $item['fkbl']=$fkbl;
                        return $item;
                    });
            }
            View::assign('punList',$punList);
            View::assign('detail',$detail);
            View::assign('id',$id);
            View::assign('mxList',$mxList);
            return view('form');
        }
    }
    public function delete()
    {
        $ids=$this->param['id']??[];
        if (!$ids){
            return to_assign(1,'参数缺失');
        }
        $status=Db::name($this->table)->where('id','in',$ids)->column('status');
        if (in_array(2,$status)){
            return to_assign(1,'参数有误');
        }

        Db::startTrans();
        try {
           $cghtMxId= Db::name($this->tableMx)->where('orderId','in',$ids)->where('status','>',-1)->column('contractMxId');
            Db::name($this->table)->where('id','in',$ids)->update(['status'=>-1,'deleted'=>time()]);
            Db::name($this->tableMx)->where('orderId','in',$ids)->where('status','>',-1)->update(['status'=>-1,'deleted'=>time()]);
           Db::name('sale_contract_detail')->where('id','in',$cghtMxId)->update(['isCgfkSelected'=>2]);
            add_log('delete', $ids, $this->param,$this->title);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return to_assign(1,'操作失败:'.$e->getMessage());
        }

        return to_assign();
    }

    public function onSure()
    {
        $id=$this->param['id']??0;
        if (!$id){
            return to_assign(1,'参数缺失');
        }
        $info=Db::name($this->table)->where('id',$id)->find();
        if (!$info||$info['status']!=1){
            return to_assign(1,'参数有误');
        }
    $mxList=Db::name('money_order_contract_detail')->where('orderId',$id)
        ->where('status','>',-1)->select();
        Db::startTrans();
        try {
            Db::name($this->table)->where('id',$id)->update([
                'checkId'=>$this->uid,
                'checkTime'=>date('Y-m-d H:i:s'),
                'status'=>2,
                'update_time'=>time()]);

            add_log('onSure', $id, $this->param,$this->title);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        foreach ($mxList as $ml){
            Db::name('money_order_contract_detail')->where('id',$ml['id'])
                ->where('status','>',-1)
                ->update(['status'=>2,'update_time'=>time()]);
            $conTractInfo=Db::name('sale_contract')
                ->where('id',$ml['contractId'])
                ->where('status',4)
                ->field("*,(select sum(money) from fy_money_order_contract_detail as mocd where mocd.status=2 and mocd.type=3 and mocd.contractId=fy_sale_contract.id)receiptedMoney")
                ->find();
            if ($conTractInfo){
                $conTractInfo['receiptedMoney']=$conTractInfo['receiptedMoney']?$conTractInfo['receiptedMoney']:0;
                $conTractInfo['unPay']=$conTractInfo['countMoney']-$conTractInfo['receiptedMoney'];
                if ($conTractInfo['countMoney']<$ml['money']){
                    throw new Exception('金额大于合同金额');
                }
                if ($conTractInfo['unPay']==$ml['money']||$conTractInfo['unPay']==0){
                    Db::name('sale_contract')->where('id',$conTractInfo['id'])
                        ->update(['payStatus'=>3,'update_time'=>time(),'payOverTime'=>date('Y-m-d H:i:s')]);
                }
                if ($conTractInfo['unPay']>$ml['money']){
                    Db::name('sale_contract')->where('id',$conTractInfo['id'])
                        ->update(['payStatus'=>2,'update_time'=>time()]);
                }

            }
            $recordData=[
                'orderDate'=>$info['orderDate'],
                'relatedOrderNum'=>$info['orderNum'],
                'purveyorId'=>$info['purveyorId'],
                'money'=>$info['money'],
                'orderType'=>$this->mType,

            ];
            moneyRecord($recordData);
        }
        return to_assign(0,'操作成功');
    }

    public function onCancel()
    {
        $id=$this->param['id']??0;
        if (!$id){
            return to_assign(1,'参数缺失');
        }
        $info=Db::name($this->table)->where('id',$id)->find();
        if (!$info||$info['status']!=2&&$info['status']!=4){
            return to_assign(1,'参数有误');
        }
        $mxList= Db::name('money_order_contract_detail')->where('orderId',$id)->where('status','>',-1)
            ->select();
        Db::startTrans();
        try {
            Db::name($this->table)->where('id',$id)->update([
                'checkId'=>$this->uid,
                'checkTime'=>date('Y-m-d H:i:s'),
                'status'=>1,
                'update_time'=>time()]);

            foreach ($mxList as $ml){
                $conTractInfo=Db::name('sale_contract')
                    ->where('id',$ml['contractId'])
                    ->where('status',4)
                    ->field("*,(select sum(money) from fy_money_order_contract_detail mocd where mocd.status=2 and type=3 and mocd.contractId=fy_sale_contract.id)receiptedMoney")
                    ->find();
                if ($conTractInfo){
                    $conTractInfo['receiptedMoney']=$conTractInfo['receiptedMoney']?$conTractInfo['receiptedMoney']:0;
                    $conTractInfo['unPay']=$conTractInfo['countMoney']-$conTractInfo['receiptedMoney']+$ml['money'];
//                if ($conTractInfo['countMoney']<$info['money']){
//                    throw new Exception('金额大于合同金额');
//                }
                    if ($conTractInfo['unPay']==$conTractInfo['countMoney']){
                        Db::name('sale_contract')->where('id',$conTractInfo['id'])
                            ->update(['payStatus'=>1,'update_time'=>time(),'payOverTime'=>null]);
                    }else if ($conTractInfo['unPay']==$ml['money']){
                            Db::name('sale_contract')->where('id',$conTractInfo['id'])
                                ->update(['payStatus'=>1,'update_time'=>time(),'payOverTime'=>null]);
                        }elseif ($conTractInfo['unPay']>$ml['money']){
                            Db::name('sale_contract')->where('id',$conTractInfo['id'])
                                ->update(['payStatus'=>2,'update_time'=>time(),'payOverTime'=>null]);
                        }
                }
            }
            Db::name('money_order_contract_detail')->where('orderId',$id)
                ->where('status','>',-1)
                ->update(['status'=>1,'update_time'=>time()]);
            $recordData=[
                'orderDate'=>$info['orderDate'],
                'relatedOrderNum'=>$info['orderNum'],
                'purveyorId'=>$info['purveyorId'],
                'money'=>$info['money'],
                'orderType'=>$this->mType,

            ];
            moneyRecord($recordData,true);
            $checkData=array(
                'action_id' => $id,
                'check_user_id' => $this->uid,
                'content' => '撤回申请',
                'type' => $this->flowType,
                'status' => 3,
                'check_time' => time(),
                'create_time' => time()
            );
            Db::name('FlowRecord')->strict(false)->field(true)->insertGetId($checkData);
            add_log('back', $id, $this->param,$this->title);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign(0,'操作成功');
    }

    public function removeMx()
    {
        $id=$this->param['id']??'';
        if (!$id){
            return to_assign(1,'参数有误');
        }
        Db::StartTrans();
        try {
            $cghtMxId= Db::name('money_order_contract_detail')->where('id','=',$id)->value('contractMxId');
            Db::name('money_order_contract_detail')
                ->where('id',$id)->update(['status'=>-1,'deleted'=>time()]);
            Db::name('sale_contract_detail')->where('id','=',$cghtMxId)
                ->update(['isCgfkSelected'=>2]);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return to_assign(1,'操作有误');
        }
        return to_assign();
    }
}